package com.netkit;

import com.netkit.message.Message;
import com.netkit.message.MessageEncoder;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelConfig;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

public class NetkitProtocolEncoder extends SimpleChannelHandler
{
  protected ChannelBuffer encode(ChannelHandlerContext context, Channel channel, Object arg)
    throws Exception
  {
    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(channel.getConfig().getBufferFactory());
    Message message = (Message)arg;
    byte[] bytes = message.getMessageContent();
    buffer.writeInt(message.getMessageId());
    buffer.writeInt(message.getContentLength());
    if (bytes != null) {
      buffer.writeBytes(bytes);
    }
    return buffer;
  }

  public void writeRequested(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception
  {
    Object msg = e.getMessage();
    if (!(msg instanceof Message)) {
      return;
    }
    byte[] bytes = MessageEncoder.encode((Message)e.getMessage());
    ChannelBuffer buf = ChannelBuffers.wrappedBuffer(bytes);
    ChannelFuture future = e.getFuture();
    Channels.write(ctx, future, buf);
  }
}